import router from "./router";
import store from "./store";
import Cookies from "js-cookie";
import { os } from "./utils/common.js";
import { getAllChildList, getLoginInfo, ticketLogin } from "@/api/member/index";

// 获取路由
function getToken() {
    try {
        const userInfo =
            Cookies.get("userInfo") != null && JSON.parse(Cookies.get("userInfo"));
        return userInfo.token || null;
    } catch (error) {
        return null;
    }
}
// "/mobile/apply/empty"
const whiteList = ['/oaLogin'];
let tokenOk = true

let codeArr = []
const getMenuCode = (MenuTree) => {
	MenuTree.map((e) => {
		codeArr.push(e.code);
		if (e.childList.length > 0) {
			getMenuCode(e.childList);
		}
	});
}

// 路由拦截
router.beforeEach(async(to, from, next) => {
    // 三方登录 如果路由是'/redirect',则调用ticketLogin登录
    if (to.path == '/redirect' && process.env.VUE_APP_LOCAL == 'fangshan') {
        // 先退出登录， 请求ticketLogin三方登录， 保存登录信息 登入系统
        const data = {
            loginType: 'user',
            ticket: to.query.ticket
        }
        ticketLogin(data).then(res => {
            codeArr = [];
            getMenuCode(res.data.nodeList);
            // 处理数据 塞到cookie中
            const userInfo = {
                name: res.data.name,
                userId: res.data.id,
                token: res.data.token,
                mobile: res.data.mobile,
                email: res.data.email,
                roleList: res.data.roleList,
                realName: res.data.realName,
                loginType: 'tripartite'
            };
            // 将用户名和 token 写入cookie 保存 / 考虑写入loaclStorage
            store.commit("app/SET_USERINFO", JSON.stringify(userInfo));
            // 读取名下子部门
            getAllChildList().then((m) => {
                res.data["childDepartmentList"] = m.data.filter(
                    (w) => w.id != res.data.departmentList[0].id
                );
                const localUserInfo = {
                    authIdArr: codeArr,
                    ...res.data,
                };
                // 将用户名等信息写入loaclStorage
                store.commit(
                    "app/SET_LOCAL_USERINFO",
                    JSON.stringify(localUserInfo)
                );
            });
            setTimeout(() => {
                next('/')
            })
        })
        return
    }
    // 如果路由中有token 放到cookie中
    if (to.query.token && tokenOk) {
			let userInfoNow
			if (Cookies.get('userInfo') == undefined) {
				userInfoNow = {
					token: to.query.token
				}
			} else {
				userInfoNow = JSON.parse(Cookies.get("userInfo"));
				userInfoNow.token = to.query.token
			}

        Cookies.set("userInfo", JSON.stringify(userInfoNow))
        // 请求接口 返回正确则  tokenOk 是true 否则 是 false
        getLoginInfo().then(res => {
					if (res.code === 200) {
							tokenOk = true
							codeArr = [];
                            getMenuCode(res.data.nodeList);
							// 处理数据 塞到cookie中
							const userInfo = {
								name: res.data.name,
								userId: res.data.id,
								token: res.data.token,
								mobile: res.data.mobile,
								email: res.data.email,
								roleList: res.data.roleList,
                                realName: res.data.realName,
							};
							// 将用户名和 token 写入cookie 保存 / 考虑写入loaclStorage
							store.commit("app/SET_USERINFO", JSON.stringify(userInfo));
							// 读取名下子部门
							getAllChildList().then((m) => {
								res.data["childDepartmentList"] = m.data.filter(
									(w) => w.id != res.data.departmentList[0].id
								);
								const localUserInfo = {
									authIdArr: codeArr,
									...res.data,
								};
								// 将用户名等信息写入loaclStorage
								store.commit(
									"app/SET_LOCAL_USERINFO",
									JSON.stringify(localUserInfo)
								);
							});
					} else {
							tokenOk = false
					}
        }).catch(err => tokenOk = false)
    }
    // 判断是否有token值
    if (getToken()) {
        // 判断菜单是否无权限控制 或者  是否有权限访问该菜单
        const currentStorage = JSON.parse(localStorage.getItem("localUserInfo"))
        let authIdArr = currentStorage && currentStorage.authIdArr || []
        let canShow = !to.meta.authCode || authIdArr.includes(to.meta.authCode);
        const isBoss = currentStorage?.childDepartmentList && currentStorage.childDepartmentList.length > 1

        if (to.path === "/login" || to.path === "/" || to.path === "/forgot-password" || to.path === '/oaLogin' || to.path === '/mobileLogin') {
            if (os.isAndroid || os.isPhone) {
                next({
                    path: to.query.redirect || "/mobile"
                }); //重定向
                return
            }
            if (isBoss) {
                next({
                    path: "/index"
                }); //重定向
            } else {
                next({
                    name: 'applyRead',
                    params: { toPath: 1 }
                }); // 非boss账户重定向到档案中心
            }
        } else if (!canShow) {
            // 无菜单权限
            if (to.path === "/retrieval/apply") {
                // boss账号进入
                next()
            } else {
                next({
                    path: "/"
                });
            }
        } else {
            next();
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单中，直接进入
            next();
        } else if (to.path === "/login" || to.path === "/forgot-password" || to.path === '/mobileLogin' || to.path === '/oaLogin') {
            next();
        } else {
            let path = "/login"
            if (os.isAndroid || os.isPhone) {
                // 移动端
                path = '/mobileLogin'
            }
            next({
                path: path,
                query: { ...to.query, redirect: to.fullPath } //将目的路由地址存入login的query中
            });
        }
    }
});